package com.demo.studyqiniu.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.demo.studyqiniu.service.IFileService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

/**
 * @description:
 * @author: jiacong
 * @time: 2020/6/8 11:02
 */
@Service
@Slf4j
public class FileServiceImpl implements IFileService {

    //七牛云配置
    @Value("${qiniu_cloud.accessKey}")
    private String qiniuAccessKey;
    @Value("${qiniu_cloud.secretKey}")
    private String qiniuSecretKey;
    @Value("${qiniu_cloud.bucket}")
    private String qiniuBucket;
    @Value("${qiniu_cloud.reqUrl}")
    private String qiniuReqUrl; //文件访问url前缀

    @Override
    public String upload(byte[] uploadBytes) throws QiniuException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
        Auth auth = Auth.create(qiniuAccessKey, qiniuSecretKey);
        String upToken = auth.uploadToken(qiniuBucket);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        log.info("==========>七牛云上传凭证token:{}",upToken);
        Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
        //解析上传成功的结果
        log.info("-->上传结果:" + JSONUtil.toJsonStr(response.bodyString()));
        JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());
        return qiniuReqUrl + jsonObject.getStr("hash");
    }
}
